﻿#if !UNITY_IOS || HUpdate
using System;
using System.IO;
using System.Linq;
using UnityEngine;

namespace UnityModule
{
    public class DownloadTask_AsycnMd5 : DownloadTask
    {
       
        public DownloadTask_AsycnMd5(string cdn, AssetBundleInfoV2 assetBundle) : base(cdn,assetBundle)
        {

        }

        private Action m_onVerify;
        public event Action OnVerify
        {
            add
            {
                m_onVerify -= value;
                m_onVerify += value;
            }
            remove
            {
                m_onVerify -= value;
            }
        }
       
        protected override void VerifyFile(Action<bool> result)
        {
            m_onVerify?.Invoke();
            if (AssetBundle.md5==null|| EmptyMd5.SequenceEqual(AssetBundle.md5))
            {
                result?.Invoke(true);
                return;
            }

            string filePath = GetSavePath();
            if (File.Exists(filePath))
            {
                MD5Utility.FileToMD5Async(filePath, (md5hash) =>
                {
                    if (md5hash.SequenceEqual(AssetBundle.md5))
                    {
                        result?.Invoke(true);
                    }
                    else
                    {
                        Debug.LogError($"{filePath}文件验证错误 {md5hash.byteToHexStr()}<>{AssetBundle.md5.byteToHexStr()}");
                        m_onError?.Invoke(emError.VerifyFail);
                    }

                }, (cur, total) =>
                {
                    //UpdateStepUtility.SetProgress(cur, total);
                });
                return;
            }
            result?.Invoke(false);
        }
    }
}
#endif